﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Documents;

namespace 写号工具
{
    public class RichTextBoxBLL
    {
        RichTextBox RichTextBoxInfo;
        public RichTextBoxBLL(RichTextBox RichTextBoxInfo)
        {
            this.RichTextBoxInfo = RichTextBoxInfo;
            RichTextBoxInfo.Document.Blocks.Clear();
        }
        /// <summary>
        /// 清空
        /// </summary>
        /// <param name="RichTextBoxInfo"></param>
        public void ClearText()
        {
            try
            {
                lock (RichTextBoxInfo)
                {
                    RichTextBoxInfo.Dispatcher.Invoke((Action)delegate
                    {
                        //清空文本
                        RichTextBoxInfo.Document.Blocks.Clear();
                        //滚动到开头
                        RichTextBoxInfo.ScrollToVerticalOffset(0);
                    });
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 写入日志
        /// </summary>
        /// <param name="RichTextBoxInfo"></param>
        /// <param name="brush"></param>
        /// <param name="txt"></param>
        public static void RichTextBoxAppendText(RichTextBox RichTextBoxInfo, System.Windows.Media.Brush brush, string txt, int size = 0)
        {
            RichTextBoxInfo.Dispatcher.Invoke((Action)delegate
            {
                var p = new Paragraph(); // Paragraph 类似于 html 的 P 标签
                var r = new Run(txt); // Run 是一个 Inline 的标签
                p.Inlines.Add(r);
                p.Foreground = brush;//设置字体颜色
                if (size != 0)
                {
                    p.FontSize = size;
                }

                p.Margin = new System.Windows.Thickness(3, 5, 3, 5);
                RichTextBoxInfo.Document.Blocks.Add(p);
                //todo 验证
                if (RichTextBoxInfo.Document.Blocks.Count > 1000)
                {
                    RichTextBoxInfo.Document.Blocks.Remove(RichTextBoxInfo.Document.Blocks.FirstBlock);
                }
                //滚动到末尾
                RichTextBoxInfo.ScrollToVerticalOffset(RichTextBoxInfo.Document.Blocks.Count * 200);
            });
        }
    }
}
